﻿using Microsoft.Web.Hosting.Administration;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;

namespace SPForms.Controls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:Captcha runat=server></{0}:Captcha>")]
    public class Captcha : WebControl
    {
        #region Controls
        Panel _pan_Row1;
        Panel _pan_Row2;
        Panel _pan_Row3;
        Image _img_Captcha;
        Label _lab_Message;
        TextBox _tb_Value;
        LinkButton _lib_TryNew;
        #endregion

        #region Properties
        public int MaxLetterCount { get; set; }
        private string GeneratedText
        {
            get
            {
                return ViewState[this.ClientID + "text"] != null ?
                    ViewState[this.ClientID + "text"].ToString() : null;
            }
            set
            {
                // Encrypt the value before storing it in viewstate.
                ViewState[this.ClientID + "text"] = value;
            }
        }
        #endregion

        protected override void CreateChildControls()
        {
            _pan_Row1 = new Panel();
            Controls.Add(_pan_Row1);
            //===================================================>>
            _img_Captcha = new Image();
            _pan_Row1.Controls.Add(_img_Captcha);
            //===================================================>>
            _pan_Row2 = new Panel();
            Controls.Add(_pan_Row2);
            //===================================================>>
            _lab_Message = new Label();
            _lab_Message.Text = "Enter the above code here:";
            _pan_Row2.Controls.Add(_lab_Message);
            //===================================================>>
            _tb_Value = new TextBox();
            _pan_Row2.Controls.Add(_tb_Value);
            //===================================================>>
            _pan_Row3 = new Panel();
            Controls.Add(_pan_Row3);
            //===================================================>>
            _lib_TryNew = new LinkButton();
            _lib_TryNew.Text = "Can&#39;t read? Try different words.";
            _lib_TryNew.Click +=_lib_TryNew_Click;
            _pan_Row3.Controls.Add(_lib_TryNew);
            //===================================================>>
            if (!Page.IsPostBack)
            {
                if (GeneratedText == null) { TryNew(); }
            }
        }

        #region ControlsEvents
        void _lib_TryNew_Click(object sender, EventArgs e)
        {
            TryNew();
        }
        #endregion

        #region Methods
        public void TryNew()
        {
            char[] Valichars = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
            string Captcha = "";
            int LetterCount = MaxLetterCount > 5 ? MaxLetterCount : 5;
            for (int i = 0; i < LetterCount; i++)
            {
                char newChar = (char)0;
                do { newChar = Char.ToUpper(Valichars[new Random(DateTime.Now.Millisecond).Next(Valichars.Count() - 1)]); }
                while (Captcha.Contains(newChar));
                Captcha += newChar;
            }
            GeneratedText = Captcha;
            byte[] _Bytes = SPForms.Common.Captcha.SecurityHelper.EncryptString(Captcha);
            string _BytesIn64String = Convert.ToBase64String(_Bytes);
            string _UrlEncoded = HttpUtility.UrlEncode(_BytesIn64String);
            _img_Captcha.ImageUrl = "/layouts/15/SPForms/captcha/GetImgText.ashx?CaptchaText=" + _UrlEncoded;
        }
        public bool IsValid
        {
            get
            {
                bool result = GeneratedText.ToUpper() == _tb_Value.Text.Trim().ToUpper();
                if (!result) { TryNew(); }
                return result;
            }
        }
        #endregion
    }
}
